﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

namespace Bilibili
{
    public partial class Form1 : Form
    {
        private string content = "";
        private int sex_man = 0;
        private int sex_women = 0;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string url = this.textBox1.Text.Trim();
            if (url.Length == 0)
            {
                MessageBox.Show("请输入URL", "提示：", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            load(url);
            loadImage();
            loadReplay();



        }

        private void load(string url)
        {
            HttpWebRequest http = (HttpWebRequest)WebRequest.Create(url);
            http.Host = "www.bilibili.com";
            http.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36";

            http.Method = "GET";
            HttpWebResponse httpWebResponse = (HttpWebResponse)http.GetResponse();
            int status = (int)httpWebResponse.StatusCode;
            if (status != 200)
                return;

            using (StreamReader stream = new StreamReader(new GZipStream(httpWebResponse.GetResponseStream(), CompressionMode.Decompress)))
            {
                this.content = stream.ReadToEnd();
            }

            var htmlDocument = new HtmlAgilityPack.HtmlDocument();
            htmlDocument.LoadHtml(this.content);
            string aid = htmlDocument.DocumentNode.SelectSingleNode(XpathCode.AID).GetAttributeValue("content", "null").Trim();
            aid = aid.Substring(aid.IndexOf("https://www.bilibili.com/video/av") + "https://www.bilibili.com/video/av".Length)
                .Replace("/", "");
            BiliInfo.SetAid(aid);
            Console.WriteLine("AID=>" + aid);
        }

        private void loadImage()
        {
            var http = new HtmlAgilityPack.HtmlDocument();
            http.LoadHtml(this.content);
            string url = http.DocumentNode.SelectSingleNode(XpathCode.IMAGE).GetAttributeValue("content", "null");
            WebRequest webRequest = WebRequest.Create(url);
            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
            int status = (int)webResponse.StatusCode;
            if (status == 200)
            {
                using (Stream stream = webResponse.GetResponseStream())
                {
                    this.pictureBox1.Image = Image.FromStream(stream);
                }
            }
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            if (this.pictureBox1.Image == null)
                return;
            SaveFileDialog save = new SaveFileDialog();
            save.Filter = "图像文件 文件(*.jpeg)|*.jpeg|图像文件 文件(*.jpg)|*.jpg|所有文件(*.*)|*.*"; ;
            if (save.ShowDialog() != DialogResult.OK)
                return;
            FileStream file = new FileStream(save.FileName, FileMode.Create, FileAccess.Write);
            this.pictureBox1.Image.Save(file, ImageFormat.Jpeg);
            MessageBox.Show("保存成功", "提示：", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            loadChart();
        }

        private void loadChart()
        {
            this.chart1.Series.Clear();
            Series series = new Series();
            series.IsValueShownAsLabel = true;
            series.Points.AddXY("男", 0);
            series.Points.AddXY("女", 0);
            series.Points.AddXY("保密", 0);
            this.chart1.Series.Add(series);
        }

        private void loadReplay()
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest
                .Create($"https://api.bilibili.com/x/v2/reply?jsonp=jsonp&pn=1&type=1&oid={BiliInfo.GetAid()}&sort=2&_=1604312467383");
            httpWebRequest.Referer = " https://www.bilibili.com/";
            httpWebRequest.Host = "api.bilibili.com";
            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            int status = (int)httpWebResponse.StatusCode;
            if (status != 200)
                return;

            using (StreamReader stream = new StreamReader(httpWebResponse.GetResponseStream()))
            {
                string json = stream.ReadToEnd();
                JObject jObject = (JObject)JsonConvert.DeserializeObject(json);
                JObject jObject1 = (JObject)jObject["data"];
                JArray jArray = (JArray)jObject1["replies"];
                this.listView1.Items.Clear();
                this.listView1.BeginUpdate();
                for (var i = 0; i < jArray.Count; i++) {
                    JObject jObject2 = (JObject)jArray[i];
                    string nickname = (string)jObject2["member"]["uname"];
                    string sex = (string)jObject2["member"]["sex"];
                    string level = (string)jObject2["member"]["level_info"]["current_level"];
                    string content = (string)jObject2["content"]["message"];
                    string time = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1))
                        .AddSeconds((int)jObject2["ctime"]).ToString();
                    string like = (string)jObject2["like"];
                    //string like = (string)jObject2["like"];
                    ListViewItem listViewItem = new ListViewItem();            
                    listViewItem.Text = nickname;
                    listViewItem.SubItems.Add(level);
                    listViewItem.SubItems.Add(content);
                    listViewItem.SubItems.Add(time);
                    listViewItem.SubItems.Add(like);
                    this.listView1.Items.Add(listViewItem);
                }
                this.listView1.EndUpdate();


            }
        }

        private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            this.listView1.BeginUpdate();
            this.listView1.ListViewItemSorter = new ListViewSort(e.Column);
            this.listView1.Sort();
            this.listView1.EndUpdate();
        }
    }
}